package com.levi.controller;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.plugins.pagination.PageHelper;
import com.github.pagehelper.PageInfo;
import com.levi.domain.School;
import com.levi.service.SchoolService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * @author shentong
 * @since 2022/8/7 13:01
 */
@RestController
@RequestMapping("/school")
public class SchoolController {

    @Autowired
    private SchoolService schoolService;

    @GetMapping
    public PageInfo query(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<School> schools = schoolService.selectAll();
        return new PageInfo(schools);
	}


    @GetMapping("/{id}")
    public void getInfo(@PathVariable("id") Long id, HttpServletResponse response) throws IOException {
        School school = schoolService.selectById(id);
        SimpleDateFormat format = new SimpleDateFormat("EEE,MMM yyyy HH: mm: ss 'GMT'", Locale.US);
        long now = System.currentTimeMillis() * 1000 * 1000;
        response.addHeader("Date", format.format(new Date()));
        response.addHeader("Expires",format.format(new Date(now + 20 * 1000)));
        response.addHeader("Cache-Control","max-age=20");
        //response.setContentType("application/json");
        //response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JSONUtil.toJsonStr(school));
	}

    @DeleteMapping("/{id}")
    public void remove(@PathVariable("id") Long id){
        schoolService.deleteById(id);
    }


    @PutMapping("/{id}")
    public void edit(@PathVariable Long id, @RequestBody School school) {
        School school1 = schoolService.selectById(id);
        BeanUtils.copyProperties(school, school1);
        school1.setId(id);
        schoolService.updateAllColumnById(school1);
    }

}
